package com.orange.delivery.spring.context;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.support.ResourcePropertySource;

/*
 * Add a PropertySource in Spring Environment. Needed when choosing a Spring profile with a property file.
 * @See http://stackoverflow.com/questions/8587489/how-to-set-active-spring-3-1-environment-profile-via-a-properites-file-and-not-v
 */
public class P13nApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

	private static final Logger LOG = LoggerFactory.getLogger(P13nApplicationContextInitializer.class);

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		try {
			// addLast because jndi, system properties and java properties are
			// searched first
			environment.getPropertySources().addLast(new ResourcePropertySource("classpath:delivery.properties"));
			LOG.info("delivery.properties loaded");
		} catch (IOException e) {
			// it's ok if the file is not there. we will just log that info.
			LOG.info("didn't find delivery.properties in classpath so not loading it in the AppContextInitialized", e);
		}
	}
}
